<?php


class Application_Model_ModelAbstract
{
    const TYPE_STUDY = 1;
    const TYPE_HOME = 2;
    const TYPE_WORK = 3;

    public static $types = array(
        self::TYPE_STUDY => "Учеба",
        self::TYPE_HOME  => "Быт",
        self::TYPE_WORK  => "Работа",
    );

    public function setOptions($options)
    {
        $methods = get_class_methods($this);

        if (!$options) {
            return false;
        }

        foreach ($options as $key => $value) {
            $pices = explode('_', $key);

            if (count($pices) > 1) {
                $key = '';
                foreach($pices as $pice) {
                    $key .= ucfirst($pice);
                }
            }

            $method = 'set' . ucfirst($key);
            if (in_array($method, $methods)) {
                $this->$method($value);
            }
        }

        return $this;
    }

    public function __construct($options = null)
    {
        if ($options) {
            $this->setOptions($options);
        }
    }

    public function toArray()
    {
        $class  = new ReflectionClass($this);
        $result = array();

        foreach ($class->getProperties() as $property) {
            if ($property->isProtected()) {
                $property->setAccessible(true);
                $value = $property->getValue($this);

                if (!is_array($property->getValue($this))) {
                    $result[$property->getName()] = $value;
                } else {
                    foreach($value as $key => $item) {
                        if ($item instanceof Application_Model_ModelAbstract) {
                            $result[$property->getName()][$key] = $item->toArray();
                        } else {
                            $result[$property->getName()] = $value;
                        }
                    }
                }
            }

            $property->setAccessible(false);
        }

        return $result;
    }
}
